package win.bigwhale.library.db.daohelper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class WhaleDaoHelper {
	private static final String MariaDBDriver = "org.mariadb.jdbc.Driver";
	private static final String WhaleLibraryDBUrl = "jdbc:mariadb://localhost:3306/whale_library";
	private static final String User = "whale";
	private static final String Password = "1900";
	private static Connection connection;

	public static Connection getConnection() {
		if (connection == null) {
			try {
				Class.forName(MariaDBDriver);
				connection = DriverManager.getConnection(WhaleLibraryDBUrl, User, Password);
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			return connection;
		}
		return connection;
	}

	public static PreparedStatement getPreparedStatement(String sql) throws SQLException {
		return getConnection().prepareStatement(sql);
	}

	public static PreparedStatement setPreparedStatement(PreparedStatement statement, ArrayList<Object> objects) throws SQLException {
		for (int i = 0; i < objects.size(); i++) {
			statement.setObject(i + 1, objects.get(i));
		}
		return statement;
	}

	public static void release(PreparedStatement statement, ResultSet set) {
		try {
			if (connection != null) {
				connection.close();
				connection = null;
			}
			if (statement != null) {
				statement.close();
				statement = null;
			}
			if (set != null) {
				set.close();
				set = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
